<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>工具导航</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#8B5CF6',
            neutral: '#1F2937',
            'base-100': '#FFFFFF',
            info: '#3ABFF8',
            success: '#36D399',
            warning: '#FBBD23',
            error: '#F87272',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
      }
      .category-transition {
        transition: all 0.3s ease;
      }
      .tool-card-hover {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
      }
      .tool-card-hover:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
      }
    }
  </style>
</head>
<body class="bg-gray-50 font-inter">
  <!-- 顶部导航栏 -->
  <header class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-compass text-primary text-2xl"></i>
        <h1 class="text-xl md:text-2xl font-bold text-primary">工具导航</h1>
      </div>
      
      <div class="hidden md:flex items-center space-x-4">
        <div class="relative">
          <input type="text" placeholder="搜索工具..." id="search-input" 
            class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all w-64">
          <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
        
        <button id="login-btn" class="hidden md:block px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-all">
          <i class="fa fa-user-circle mr-2"></i>登录
        </button>
        
        <button id="admin-btn" class="hidden md:block px-4 py-2 rounded-lg bg-secondary text-white hover:bg-secondary/90 transition-all">
          <i class="fa fa-cog mr-2"></i>管理
        </button>
      </div>
      
      <button id="mobile-menu-btn" class="md:hidden text-gray-700 focus:outline-none">
        <i class="fa fa-bars text-xl"></i>
      </button>
    </div>
    
    <!-- 移动端菜单 -->
    <div id="mobile-menu" class="hidden md:hidden bg-white border-t">
      <div class="container mx-auto px-4 py-3 space-y-3">
        <div class="relative">
          <input type="text" placeholder="搜索工具..." 
            class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all w-full">
          <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
        
        <div class="flex space-x-2">
          <button id="mobile-login-btn" class="flex-1 px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-all">
            <i class="fa fa-user-circle mr-2"></i>登录
          </button>
          
          <button id="mobile-admin-btn" class="flex-1 px-4 py-2 rounded-lg bg-secondary text-white hover:bg-secondary/90 transition-all">
            <i class="fa fa-cog mr-2"></i>管理
          </button>
        </div>
      </div>
    </div>
  </header>

  <!-- 主要内容区 -->
  <main class="container mx-auto px-4 py-6">
    <!-- 分类导航 -->
    <div class="mb-8 overflow-x-auto">
      <div class="flex space-x-2 pb-2 min-w-max">
        <button class="category-btn active px-4 py-2 rounded-full bg-primary text-white" data-category="all">
          全部
        </button>
        <button class="category-btn px-4 py-2 rounded-full bg-gray-200 hover:bg-gray-300 transition-all" data-category="development">
          <i class="fa fa-code mr-1"></i>开发工具
        </button>
        <button class="category-btn px-4 py-2 rounded-full bg-gray-200 hover:bg-gray-300 transition-all" data-category="design">
          <i class="fa fa-paint-brush mr-1"></i>设计工具
        </button>
        <button class="category-btn px-4 py-2 rounded-full bg-gray-200 hover:bg-gray-300 transition-all" data-category="productivity">
          <i class="fa fa-tasks mr-1"></i>效率工具
        </button>
        <button class="category-btn px-4 py-2 rounded-full bg-gray-200 hover:bg-gray-300 transition-all" data-category="communication">
          <i class="fa fa-comments mr-1"></i>沟通工具
        </button>
        <button class="category-btn px-4 py-2 rounded-full bg-gray-200 hover:bg-gray-300 transition-all" data-category="learning">
          <i class="fa fa-graduation-cap mr-1"></i>学习资源
        </button>
      </div>
    </div>
    
    <!-- 工具列表 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6" id="tools-container">
      <!-- 工具卡片将通过JavaScript动态生成 -->
    </div>
    
    <!-- 没有结果提示 -->
    <div id="no-results" class="hidden text-center py-12">
      <i class="fa fa-search text-4xl text-gray-400 mb-4"></i>
      <p class="text-gray-600">没有找到匹配的工具</p>
    </div>
  </main>

  <!-- 管理面板模态框 -->
  <div id="admin-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h2 class="text-xl font-bold text-gray-800">管理面板</h2>
          <button id="close-admin-modal" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      
      <div class="p-6">
        <!-- 管理面板标签页 -->
        <div class="border-b mb-6">
          <div class="flex space-x-4">
            <button class="admin-tab-btn active px-4 py-2 text-primary border-b-2 border-primary font-medium" data-tab="categories">
              分类管理
            </button>
            <button class="admin-tab-btn px-4 py-2 text-gray-500 hover:text-gray-700" data-tab="tools">
              工具管理
            </button>
          </div>
        </div>
        
        <!-- 分类管理标签页 -->
        <div id="categories-tab" class="admin-tab-content">
          <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-semibold text-gray-800">分类列表</h3>
            <button id="add-category-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all">
              <i class="fa fa-plus mr-2"></i>新增分类
            </button>
          </div>
          
          <div class="bg-gray-50 rounded-lg p-4 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">分类名称</label>
                <input type="text" id="new-category-name" placeholder="输入分类名称" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">分类图标 (Font Awesome 类名)</label>
                <input type="text" id="new-category-icon" placeholder="例如: fa-code" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              </div>
            </div>
            <div class="mt-4 flex justify-end">
              <button id="save-new-category" class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-all">
                <i class="fa fa-save mr-2"></i>保存
              </button>
            </div>
          </div>
          
          <div class="overflow-x-auto">
            <table class="min-w-full bg-white rounded-lg overflow-hidden">
              <thead class="bg-gray-100">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图标</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类名称</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工具数量</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody id="categories-table-body">
                <!-- 分类表格内容将通过JavaScript动态生成 -->
              </tbody>
            </table>
          </div>
        </div>
        
        <!-- 工具管理标签页 -->
        <div id="tools-tab" class="admin-tab-content hidden">
          <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-semibold text-gray-800">工具列表</h3>
            <button id="add-tool-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all">
              <i class="fa fa-plus mr-2"></i>新增工具
            </button>
          </div>
          
          <div class="bg-gray-50 rounded-lg p-4 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">工具名称</label>
                <input type="text" id="new-tool-name" placeholder="输入工具名称" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">工具URL</label>
                <input type="text" id="new-tool-url" placeholder="输入工具URL" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">工具描述</label>
                <input type="text" id="new-tool-desc" placeholder="输入工具描述" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属分类</label>
                <select id="new-tool-category" 
                  class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                  <!-- 分类选项将通过JavaScript动态生成 -->
                </select>
              </div>
            </div>
            <div class="mt-4 flex justify-end">
              <button id="save-new-tool" class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-all">
                <i class="fa fa-save mr-2"></i>保存
              </button>
            </div>
          </div>
          
          <div class="overflow-x-auto">
            <table class="min-w-full bg-white rounded-lg overflow-hidden">
              <thead class="bg-gray-100">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工具名称</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody id="tools-table-body">
                <!-- 工具表格内容将通过JavaScript动态生成 -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 编辑分类模态框 -->
  <div id="edit-category-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h2 class="text-xl font-bold text-gray-800">编辑分类</h2>
          <button id="close-edit-category-modal" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      
      <div class="p-6">
        <input type="hidden" id="edit-category-id">
        <div class="grid grid-cols-1 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">分类名称</label>
            <input type="text" id="edit-category-name" placeholder="输入分类名称" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">分类图标 (Font Awesome 类名)</label>
            <input type="text" id="edit-category-icon" placeholder="例如: fa-code" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-3">
          <button id="delete-category-btn" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-all">
            <i class="fa fa-trash mr-2"></i>删除
          </button>
          <button id="save-edited-category" class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-all">
            <i class="fa fa-save mr-2"></i>保存
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 编辑工具模态框 -->
  <div id="edit-tool-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h2 class="text-xl font-bold text-gray-800">编辑工具</h2>
          <button id="close-edit-tool-modal" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      
      <div class="p-6">
        <input type="hidden" id="edit-tool-id">
        <div class="grid grid-cols-1 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">工具名称</label>
            <input type="text" id="edit-tool-name" placeholder="输入工具名称" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">工具URL</label>
            <input type="text" id="edit-tool-url" placeholder="输入工具URL" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">工具描述</label>
            <input type="text" id="edit-tool-desc" placeholder="输入工具描述" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">所属分类</label>
            <select id="edit-tool-category" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
              <!-- 分类选项将通过JavaScript动态生成 -->
            </select>
          </div>
        </div>
        <div class="mt-6 flex justify-end space-x-3">
          <button id="delete-tool-btn" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-all">
            <i class="fa fa-trash mr-2"></i>删除
          </button>
          <button id="save-edited-tool" class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-all">
            <i class="fa fa-save mr-2"></i>保存
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 登录模态框 -->
  <div id="login-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl w-full max-w-md">
      <div class="p-6 border-b">
        <div class="flex justify-between items-center">
          <h2 class="text-xl font-bold text-gray-800">管理员登录</h2>
          <button id="close-login-modal" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
      </div>
      
      <div class="p-6">
        <div class="grid grid-cols-1 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
            <input type="text" id="login-username" placeholder="输入用户名" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
            <input type="password" id="login-password" placeholder="输入密码" 
              class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
          </div>
        </div>
        <div class="mt-6">
          <button id="login-submit" class="w-full px-4 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all">
            <i class="fa fa-sign-in mr-2"></i>登录
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 消息提示 -->
  <div id="toast" class="fixed top-4 right-4 bg-gray-800 text-white px-6 py-3 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300 z-50 flex items-center">
    <i id="toast-icon" class="fa fa-check-circle mr-2"></i>
    <span id="toast-message">操作成功</span>
  </div>

  <script>
    // 模拟数据 - 在实际应用中，这些数据将从Flask后端获取
    let categories = [
      { id: 1, name: "开发工具", icon: "fa-code", color: "#165DFF" },
      { id: 2, name: "设计工具", icon: "fa-paint-brush", color: "#36D399" },
      { id: 3, name: "效率工具", icon: "fa-tasks", color: "#8B5CF6" },
      { id: 4, name: "沟通工具", icon: "fa-comments", color: "#FBBD23" },
      { id: 5, name: "学习资源", icon: "fa-graduation-cap", color: "#F87272" }
    ];
    
    let tools = [
      { id: 1, name: "GitHub", url: "https://github.com", description: "代码托管平台", category_id: 1 },
      { id: 2, name: "VS Code", url: "https://code.visualstudio.com", description: "强大的代码编辑器", category_id: 1 },
      { id: 3, name: "Figma", url: "https://figma.com", description: "在线UI设计工具", category_id: 2 },
      { id: 4, name: "Adobe Photoshop", url: "https://www.adobe.com/products/photoshop.html", description: "专业图像处理软件", category_id: 2 },
      { id: 5, name: "Trello", url: "https://trello.com", description: "项目管理工具", category_id: 3 },
      { id: 6, name: "Notion", url: "https://notion.so", description: "一体化工作空间", category_id: 3 },
      { id: 7, name: "Slack", url: "https://slack.com", description: "团队沟通工具", category_id: 4 },
      { id: 8, name: "Zoom", url: "https://zoom.us", description: "视频会议平台", category_id: 4 },
      { id: 9, name: "MDN Web Docs", url: "https://developer.mozilla.org", description: "Web开发文档", category_id: 5 },
      { id: 10, name: "Coursera", url: "https://coursera.org", description: "在线学习平台", category_id: 5 }
    ];
    
    // 当前用户状态（模拟）
    let currentUser = null;
    
    // DOM 元素
    const toolsContainer = document.getElementById('tools-container');
    const searchInput = document.getElementById('search-input');
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    const mobileMenu = document.getElementById('mobile-menu');
    const categoryBtns = document.querySelectorAll('.category-btn');
    const adminBtn = document.getElementById('admin-btn');
    const mobileAdminBtn = document.getElementById('mobile-admin-btn');
    const loginBtn = document.getElementById('login-btn');
    const mobileLoginBtn = document.getElementById('mobile-login-btn');
    const adminModal = document.getElementById('admin-modal');
    const closeAdminModal = document.getElementById('close-admin-modal');
    const adminTabBtns = document.querySelectorAll('.admin-tab-btn');
    const adminTabContents = document.querySelectorAll('.admin-tab-content');
    const categoriesTableBody = document.getElementById('categories-table-body');
    const toolsTableBody = document.getElementById('tools-table-body');
    const newCategoryName = document.getElementById('new-category-name');
    const newCategoryIcon = document.getElementById('new-category-icon');
    const saveNewCategory = document.getElementById('save-new-category');
    const addCategoryBtn = document.getElementById('add-category-btn');
    const newToolName = document.getElementById('new-tool-name');
    const newToolUrl = document.getElementById('new-tool-url');
    const newToolDesc = document.getElementById('new-tool-desc');
    const newToolCategory = document.getElementById('new-tool-category');
    const saveNewTool = document.getElementById('save-new-tool');
    const addToolBtn = document.getElementById('add-tool-btn');
    const editCategoryModal = document.getElementById('edit-category-modal');
    const closeEditCategoryModal = document.getElementById('close-edit-category-modal');
    const editCategoryId = document.getElementById('edit-category-id');
    const editCategoryName = document.getElementById('edit-category-name');
    const editCategoryIcon = document.getElementById('edit-category-icon');
    const saveEditedCategory = document.getElementById('save-edited-category');
    const deleteCategoryBtn = document.getElementById('delete-category-btn');
    const editToolModal = document.getElementById('edit-tool-modal');
    const closeEditToolModal = document.getElementById('close-edit-tool-modal');
    const editToolId = document.getElementById('edit-tool-id');
    const editToolName = document.getElementById('edit-tool-name');
    const editToolUrl = document.getElementById('edit-tool-url');
    const editToolDesc = document.getElementById('edit-tool-desc');
    const editToolCategory = document.getElementById('edit-tool-category');
    const saveEditedTool = document.getElementById('save-edited-tool');
    const deleteToolBtn = document.getElementById('delete-tool-btn');
    const loginModal = document.getElementById('login-modal');
    const closeLoginModal = document.getElementById('close-login-modal');
    const loginUsername = document.getElementById('login-username');
    const loginPassword = document.getElementById('login-password');
    const loginSubmit = document.getElementById('login-submit');
    const toast = document.getElementById('toast');
    const toastMessage = document.getElementById('toast-message');
    const toastIcon = document.getElementById('toast-icon');
    const noResults = document.getElementById('no-results');
    
    // 初始化页面
    function init() {
      renderTools();
      renderCategoriesTable();
      renderToolsTable();
      renderCategorySelectOptions();
      renderEditCategorySelectOptions();
      
      // 监听事件
      mobileMenuBtn.addEventListener('click', toggleMobileMenu);
      categoryBtns.forEach(btn => btn.addEventListener('click', filterTools));
      adminBtn.addEventListener('click', toggleAdminModal);
      mobileAdminBtn.addEventListener('click', toggleAdminModal);
      loginBtn.addEventListener('click', toggleLoginModal);
      mobileLoginBtn.addEventListener('click', toggleLoginModal);
      closeAdminModal.addEventListener('click', toggleAdminModal);
      adminTabBtns.forEach(btn => btn.addEventListener('click', switchAdminTab));
      saveNewCategory.addEventListener('click', addCategory);
      addCategoryBtn.addEventListener('click', resetNewCategoryForm);
      saveNewTool.addEventListener('click', addTool);
      addToolBtn.addEventListener('click', resetNewToolForm);
      closeEditCategoryModal.addEventListener('click', toggleEditCategoryModal);
      saveEditedCategory.addEventListener('click', updateCategory);
      deleteCategoryBtn.addEventListener('click', deleteCategory);
      closeEditToolModal.addEventListener('click', toggleEditToolModal);
      saveEditedTool.addEventListener('click', updateTool);
      deleteToolBtn.addEventListener('click', deleteTool);
      closeLoginModal.addEventListener('click', toggleLoginModal);
      loginSubmit.addEventListener('click', handleLogin);
      searchInput.addEventListener('input', filterToolsBySearch);
      
      // 模拟用户已登录状态
      simulateLogin();
    }
    
    // 模拟用户登录
    function simulateLogin() {
      currentUser = { username: "admin" };
      updateLoginStatus();
    }
    
    // 更新登录状态
    function updateLoginStatus() {
      if (currentUser) {
        loginBtn.innerHTML = `<i class="fa fa-user-circle mr-2"></i>${currentUser.username}`;
        mobileLoginBtn.innerHTML = `<i class="fa fa-user-circle mr-2"></i>${currentUser.username}`;
      }
    }
    
    // 处理登录
    function handleLogin() {
      const username = loginUsername.value;
      const password = loginPassword.value;
      
      // 模拟登录验证
      if (username === "admin" && password === "admin") {
        currentUser = { username };
        updateLoginStatus();
        toggleLoginModal();
        showToast("登录成功", "success");
      } else {
        showToast("用户名或密码错误", "error");
      }
    }
    
    // 渲染工具列表
    function renderTools(filteredTools = null) {
      toolsContainer.innerHTML = '';
      const toolsToRender = filteredTools || tools;
      
      if (toolsToRender.length === 0) {
        noResults.classList.remove('hidden');
        return;
      }
      
      noResults.classList.add('hidden');
      
      toolsToRender.forEach(tool => {
        const category = categories.find(c => c.id === tool.category_id);
        if (!category) return;
        
        const toolCard = document.createElement('div');
        toolCard.className = 'bg-white rounded-xl overflow-hidden shadow-md tool-card-hover';
        toolCard.innerHTML = `
          <div class="p-5">
            <div class="flex items-start">
              <div class="w-10 h-10 rounded-lg bg-${getColorClass(category.color)} flex items-center justify-center text-white mr-3">
                <i class="fa ${category.icon}"></i>
              </div>
              <div class="flex-1">
                <h3 class="text-lg font-semibold text-gray-800 mb-1">
                  <a href="${tool.url}" target="_blank" class="hover:text-primary transition-colors">${tool.name}</a>
                </h3>
                <p class="text-gray-600 text-sm">${tool.description}</p>
              </div>
              ${currentUser ? `<div class="text-gray-400 hover:text-gray-600 cursor-pointer" onclick="openEditToolModal(${tool.id})">
                <i class="fa fa-pencil"></i>
              </div>` : ''}
            </div>
            <div class="mt-4 flex items-center text-xs text-gray-500">
              <span class="px-2 py-1 rounded-full bg-${getColorClass(category.color)}/10 text-${getColorClass(category.color)}">
                <i class="fa ${category.icon} mr-1"></i>${category.name}
              </span>
            </div>
          </div>
        `;
        
        toolsContainer.appendChild(toolCard);
      });
    }
    
    // 辅助函数：获取颜色类名
    function getColorClass(color) {
      const colorMap = {
        '#165DFF': 'primary',
        '#36D399': 'secondary',
        '#8B5CF6': 'accent',
        '#FBBD23': 'warning',
        '#F87272': 'error'
      };
      return colorMap[color] || 'primary';
    }
    
    // 渲染分类表格
    function renderCategoriesTable() {
      categoriesTableBody.innerHTML = '';
      
      categories.forEach(category => {
        const row = document.createElement('tr');
        row.className = 'border-b hover:bg-gray-50 transition-colors';
        row.innerHTML = `
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${category.id}</td>
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="w-8 h-8 rounded-lg bg-${getColorClass(category.color)} flex items-center justify-center text-white">
              <i class="fa ${category.icon}"></i>
            </div>
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="text-sm font-medium text-gray-900">${category.name}</div>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            ${tools.filter(t => t.category_id === category.id).length}
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            <button class="text-blue-600 hover:text-blue-900 mr-3" onclick="openEditCategoryModal(${category.id})">
              <i class="fa fa-pencil"></i> 编辑
            </button>
          </td>
        `;
        
        categoriesTableBody.appendChild(row);
      });
    }
    
    // 渲染工具表格
    function renderToolsTable() {
      toolsTableBody.innerHTML = '';
      
      tools.forEach(tool => {
        const category = categories.find(c => c.id === tool.category_id);
        if (!category) return;
        
        const row = document.createElement('tr');
        row.className = 'border-b hover:bg-gray-50 transition-colors';
        row.innerHTML = `
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${tool.id}</td>
          <td class="px-6 py-4 whitespace-nowrap">
            <div class="text-sm font-medium text-gray-900">${tool.name}</div>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            ${tool.description}
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <span class="px-2 py-1 rounded-full bg-${getColorClass(category.color)}/10 text-${getColorClass(category.color)} text-xs">
              ${category.name}
            </span>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            <button class="text-blue-600 hover:text-blue-900 mr-3" onclick="openEditToolModal(${tool.id})">
              <i class="fa fa-pencil"></i> 编辑
            </button>
          </td>
        `;
        
        toolsTableBody.appendChild(row);
      });
    }
    
    // 渲染分类选择框选项
    function renderCategorySelectOptions() {
      newToolCategory.innerHTML = '';
      
      categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.id;
        option.textContent = category.name;
        newToolCategory.appendChild(option);
      });
    }
    
    // 渲染编辑工具模态框中的分类选择框选项
    function renderEditCategorySelectOptions() {
      editToolCategory.innerHTML = '';
      
      categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.id;
        option.textContent = category.name;
        editToolCategory.appendChild(option);
      });
    }
    
    // 过滤工具
    function filterTools() {
      const category = this.dataset.category;
      
      // 更新活跃分类按钮样式
      categoryBtns.forEach(btn => {
        btn.classList.remove('active', 'bg-primary', 'text-white');
        btn.classList.add('bg-gray-200', 'hover:bg-gray-300');
      });
      
      this.classList.add('active', 'bg-primary', 'text-white');
      this.classList.remove('bg-gray-200', 'hover:bg-gray-300');
      
      if (category === 'all') {
        renderTools();
      } else {
        const categoryObj = categories.find(c => c.name.toLowerCase().replace(/\s+/g, '-') === category);
        if (categoryObj) {
          const filteredTools = tools.filter(tool => tool.category_id === categoryObj.id);
          renderTools(filteredTools);
        }
      }
    }
    
    // 通过搜索框过滤工具
    function filterToolsBySearch() {
      const searchTerm = this.value.toLowerCase().trim();
      
      if (!searchTerm) {
        renderTools();
        return;
      }
      
      const filteredTools = tools.filter(tool => 
        tool.name.toLowerCase().includes(searchTerm) || 
        tool.description.toLowerCase().includes(searchTerm)
      );
      
      renderTools(filteredTools);
    }
    
    // 切换移动菜单
    function toggleMobileMenu() {
      mobileMenu.classList.toggle('hidden');
    }
    
    // 切换管理模态框
    function toggleAdminModal() {
      if (!currentUser) {
        toggleLoginModal();
        return;
      }
      
      adminModal.classList.toggle('hidden');
    }
    
    // 切换登录模态框
    function toggleLoginModal() {
      loginModal.classList.toggle('hidden');
    }
    
    // 切换编辑分类模态框
    function toggleEditCategoryModal() {
      editCategoryModal.classList.toggle('hidden');
    }
    
    // 切换编辑工具模态框
    function toggleEditToolModal() {
      editToolModal.classList.toggle('hidden');
    }
    
    // 打开编辑分类模态框
    function openEditCategoryModal(id) {
      const category = categories.find(c => c.id === id);
      if (!category) return;
      
      editCategoryId.value = category.id;
      editCategoryName.value = category.name;
      editCategoryIcon.value = category.icon;
      
      toggleEditCategoryModal();
    }
    
    // 打开编辑工具模态框
    function openEditToolModal(id) {
      const tool = tools.find(t => t.id === id);
      if (!tool) return;
      
      editToolId.value = tool.id;
      editToolName.value = tool.name;
      editToolUrl.value = tool.url;
      editToolDesc.value = tool.description;
      editToolCategory.value = tool.category_id;
      
      toggleEditToolModal();
    }
    
    // 重置新增分类表单
    function resetNewCategoryForm() {
      newCategoryName.value = '';
      newCategoryIcon.value = '';
    }
    
    // 重置新增工具表单
    function resetNewToolForm() {
      newToolName.value = '';
      newToolUrl.value = '';
      newToolDesc.value = '';
    }
    
    // 切换管理面板标签页
    function switchAdminTab() {
      const tab = this.dataset.tab;
      
      // 更新活跃标签按钮样式
      adminTabBtns.forEach(btn => {
        btn.classList.remove('active', 'text-primary', 'border-b-2', 'border-primary');
        btn.classList.add('text-gray-500', 'hover:text-gray-700');
      });
      
      this.classList.add('active', 'text-primary', 'border-b-2', 'border-primary');
      this.classList.remove('text-gray-500', 'hover:text-gray-700');
      
      // 显示对应标签页内容
      adminTabContents.forEach(content => {
        content.classList.add('hidden');
      });
      
      document.getElementById(`${tab}-tab`).classList.remove('hidden');
    }
    
    // 添加分类
    function addCategory() {
      const name = newCategoryName.value.trim();
      const icon = newCategoryIcon.value.trim();
      
      if (!name || !icon) {
        showToast("请填写分类名称和图标", "error");
        return;
      }
      
      // 生成新分类ID
      const newId = Math.max(0, ...categories.map(c => c.id)) + 1;
      
      // 创建新分类
      const newCategory = {
        id: newId,
        name,
        icon,
        color: getRandomColor()
      };
      
      // 添加到分类列表
      categories.push(newCategory);
      
      // 更新UI
      renderCategoriesTable();
      renderCategorySelectOptions();
      renderEditCategorySelectOptions();
      resetNewCategoryForm();
      
      // 显示成功消息
      showToast("分类添加成功", "success");
    }
    
    // 更新分类
    function updateCategory() {
      const id = parseInt(editCategoryId.value);
      const name = editCategoryName.value.trim();
      const icon = editCategoryIcon.value.trim();
      
      if (!name || !icon) {
        showToast("请填写分类名称和图标", "error");
        return;
      }
      
      // 查找要更新的分类
      const categoryIndex = categories.findIndex(c => c.id === id);
      
      if (categoryIndex === -1) {
        showToast("分类不存在", "error");
        return;
      }
      
      // 更新分类信息
      categories[categoryIndex] = {
        ...categories[categoryIndex],
        name,
        icon
      };
      
      // 更新相关工具的分类名称显示
      tools.forEach(tool => {
        if (tool.category_id === id) {
          // 更新工具卡片中使用了分类的部分
          // 这里在实际应用中可能需要更复杂的更新逻辑
        }
      });
      
      // 更新UI
      renderCategoriesTable();
      renderCategorySelectOptions();
      renderEditCategorySelectOptions();
      renderTools();
      
      // 关闭模态框
      toggleEditCategoryModal();
      
      // 显示成功消息
      showToast("分类更新成功", "success");
    }
    
    // 删除分类
    function deleteCategory() {
      const id = parseInt(editCategoryId.value);
      
      // 检查是否有工具使用此分类
      const toolsInCategory = tools.filter(tool => tool.category_id === id);
      
      if (toolsInCategory.length > 0) {
        showToast("此分类下有工具，不能删除", "error");
        return;
      }
      
      // 从分类列表中删除
      categories = categories.filter(c => c.id !== id);
      
      // 更新UI
      renderCategoriesTable();
      renderCategorySelectOptions();
      renderEditCategorySelectOptions();
      
      // 关闭模态框
      toggleEditCategoryModal();
      
      // 显示成功消息
      showToast("分类删除成功", "success");
    }
    
    // 添加工具
    function addTool() {
      const name = newToolName.value.trim();
      const url = newToolUrl.value.trim();
      const desc = newToolDesc.value.trim();
      const categoryId = parseInt(newToolCategory.value);
      
      if (!name || !url) {
        showToast("请填写工具名称和URL", "error");
        return;
      }
      
      // 生成新工具ID
      const newId = Math.max(0, ...tools.map(t => t.id)) + 1;
      
      // 创建新工具
      const newTool = {
        id: newId,
        name,
        url,
        description: desc,
        category_id: categoryId
      };
      
      // 添加到工具列表
      tools.push(newTool);
      
      // 更新UI
      renderToolsTable();
      renderTools();
      resetNewToolForm();
      
      // 显示成功消息
      showToast("工具添加成功", "success");
    }
    
    // 更新工具
    function updateTool() {
      const id = parseInt(editToolId.value);
      const name = editToolName.value.trim();
      const url = editToolUrl.value.trim();
      const desc = editToolDesc.value.trim();
      const categoryId = parseInt(editToolCategory.value);
      
      if (!name || !url) {
        showToast("请填写工具名称和URL", "error");
        return;
      }
      
      // 查找要更新的工具
      const toolIndex = tools.findIndex(t => t.id === id);
      
      if (toolIndex === -1) {
        showToast("工具不存在", "error");
        return;
      }
      
      // 更新工具信息
      tools[toolIndex] = {
        ...tools[toolIndex],
        name,
        url,
        description: desc,
        category_id: categoryId
      };
      
      // 更新UI
      renderToolsTable();
      renderTools();
      
      // 关闭模态框
      toggleEditToolModal();
      
      // 显示成功消息
      showToast("工具更新成功", "success");
    }
    
    // 删除工具
    function deleteTool() {
      const id = parseInt(editToolId.value);
      
      // 从工具列表中删除
      tools = tools.filter(t => t.id !== id);
      
      // 更新UI
      renderToolsTable();
      renderTools();
      
      // 关闭模态框
      toggleEditToolModal();
      
      // 显示成功消息
      showToast("工具删除成功", "success");
    }
    
    // 显示提示消息
    function showToast(message, type = "success") {
      toastMessage.textContent = message;
      
      // 设置图标和颜色
      if (type === "success") {
        toastIcon.className = "fa fa-check-circle mr-2";
        toast.classList.remove("bg-red-500");
        toast.classList.add("bg-green-500");
      } else if (type === "error") {
        toastIcon.className = "fa fa-exclamation-circle mr-2";
        toast.classList.remove("bg-green-500");
        toast.classList.add("bg-red-500");
      }
      
      // 显示提示
      toast.classList.remove("translate-x-full");
      
      // 3秒后隐藏
      setTimeout(() => {
        toast.classList.add("translate-x-full");
      }, 3000);
    }
    
    // 获取随机颜色
    function getRandomColor() {
      const colors = [
        '#165DFF', '#36D399', '#8B5CF6', '#FBBD23', '#F87272',
        '#EC4899', '#10B981', '#3B82F6', '#6366F1', '#F97316'
      ];
      return colors[Math.floor(Math.random() * colors.length)];
    }
    
    // 使函数在全局作用域中可用
    window.openEditCategoryModal = openEditCategoryModal;
    window.openEditToolModal = openEditToolModal;
    
    // 初始化页面
    document.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>    